-- ************************************************************************************************************************
-- LeaderScene
-- 描述：一个无交互的视差UI场景，位于3D领导者和外交UI上下文之下
-- 行为：此场景监听领导者选择的变化，相应地改变纹理，并在新纹理上播放视差动画
-- 交互对象：DiplomacyActionView，DiplomacyView和DiplomacyDealView
-- ------------------------------------------------------------------------------------------------------------------------
include( "InstanceManager" );
include( "SupportFunctions" );

-- 成员变量
local m_kBackgroundLayersIM :table = InstanceManager:new( "Layer",  "Background_Anim", Controls.Backgrounds );
local m_uiBackgroundLayers : table = {};
local m_isViewInitialized : boolean = false;
local m_oldLeaderName : string = "";
-- 常量
local PARALLAX_DISTANCE : number = 100;
local m_isTutorial : boolean = false;

local TUTORIAL_ID :string = "17462E0F-1EE1-4819-AAAA-052B5896B02A";

-- ------------------------------------------------------------------------------------------------------------------------
-- Parallax: 简单函数，用于从左到右Tween一个分层场景，并模拟简单的视差效果
-- distance: 图层应旅行的总距离（像素）
function Parallax(distance: number)
    SizeBackgrounds();
    local numLayers = table.count(m_uiBackgroundLayers);
    local spacing = distance/numLayers;
    local rightToLeft : boolean = false;
    for layer = numLayers,1,-1 do
        if (layer == numLayers) then -- 第N层或“视窗”应静止，大小为屏幕全尺寸并居中
            m_uiBackgroundLayers[layer].Background_Anim:SetAnchor("C,C");
            m_uiBackgroundLayers[layer].Background_Image:SetAnchor("C,C");
            m_uiBackgroundLayers[layer].Background_Anim:ReprocessAnchoring();
            m_uiBackgroundLayers[layer].Background_Image:ReprocessAnchoring();
        else
            m_uiBackgroundLayers[layer].Background_Anim:SetBeginVal(-distance, 0); -- 剩余图层应进行视差行为
            m_uiBackgroundLayers[layer].Background_Anim:SetEndVal(0, 0);
        end
        m_uiBackgroundLayers[layer].Background_Anim:SetSpeed(.2);
        m_uiBackgroundLayers[layer].Background_Anim:SetToBeginning();
        m_uiBackgroundLayers[layer].Background_Anim:Play();
        distance = distance-spacing;
    end
end

-- 根据提供的player_ID创建适当图层。
-- selectedPlayerID - 应该显示其背景的领导者的ID
function GenerateLayers(selectedPlayerID:number)
    local playerConfig = PlayerConfigurations[selectedPlayerID];
    if (playerConfig ~= nil) then
        
        m_uiBackgroundLayers = {};
        m_kBackgroundLayersIM:ResetInstances();

        local leaderName = playerConfig:GetLeaderTypeName();
        local unloadTextures : boolean = m_oldLeaderName ~= leaderName;
        m_oldLeaderName = leaderName;

        local diplomacyInfo = GameInfo.DiplomacyInfo[leaderName];
        if diplomacyInfo and diplomacyInfo.BackgroundImage then
            local layer:table = CreateBackgroundLayer(diplomacyInfo.BackgroundImage, unloadTextures);
            table.insert(m_uiBackgroundLayers, layer);
        else
            local numLayers = GameInfo.Leaders[leaderName].SceneLayers;
            leaderName = string.gsub(leaderName, "LEADER_","");

            -- 安全回退
            if (numLayers == 0) then
                leaderName = "CLEOPATRA";
                numLayers = 4;
            end

            for i=1, numLayers, 1 do
                local layer:table = CreateBackgroundLayer(leaderName.."_"..i, unloadTextures);
                table.insert(m_uiBackgroundLayers, layer);
            end
        end
    end
end

-- 创建背景图层。
-- texture:string - 要设置的纹理。
-- unloadTextures:boolean - 是否卸载旧纹理。
function CreateBackgroundLayer(texture:string, unloadTextures:boolean)
    local instance:table = m_kBackgroundLayersIM:GetInstance();
    if (unloadTextures) then
        instance.Background_Image:UnloadTexture();
    end
    instance.Background_Image:SetTexture(texture);
    return instance;
end

-- 此函数正确调整背景图像的大小。第1-3层垂直尺寸缩小200像素，以便在字母框中看到大部分场景。
-- 最后一层 - “视窗” - 可以拉伸到屏幕的全尺寸
function SizeBackgrounds()
    local numLayers = table.count(m_uiBackgroundLayers);
    --local adjustedWidth = adjustedY*1.9; -- TODO
    for layer = 1,numLayers,1 do
        if(not layer == numLayers) then
            m_uiBackgroundLayers[layer].Background_Anim:SetParentRelativeSizeY(-200);
            m_uiBackgroundLayers[layer].Background_Anim:ReprocessAnchoring();
            m_uiBackgroundLayers[layer].Background_Image:SetParentRelativeSizeY(-200);
            m_uiBackgroundLayers[layer].Background_Image:ReprocessAnchoring();
        end
    end
end

-- ------------------------------------------------------------------------------------------------------------------------
-- LUA事件处理
-- 监听领导者选择的变化，并更新背景图像以对应此选择
function OnLeaderSelect(selectedPlayerID)
    GenerateLayers(selectedPlayerID);
    Parallax(PARALLAX_DISTANCE);
end
-- ------------------------------------------------------------------------------------------------------------------------
-- DiploActionView通知我们领导者已加载。
function OnSceneOpened(selectedPlayerID, liteMode)
    if(selectedPlayerID ~= nil) then
        GenerateLayers(selectedPlayerID);
    end
    if (ContextPtr:IsHidden()) then
        ContextPtr:SetHide(false);
        InitializeView(liteMode);
    end
end
-- ------------------------------------------------------------------------------------------------------------------------
-- InitializeView 和 UninitializeView
-- 这些函数允许我们等待领导者完全加载后再显示上下文。
function InitializeView(liteMode)
    if (not m_isViewInitialized) then
        m_isViewInitialized = true;
        if (m_isTutorial == false and not liteMode) then
            UIManager:DisablePopupQueue( true );		-- 等待此功能被Forge添加
        end
    end
end

function UninitializeView()
    if (m_isViewInitialized) then
        ContextPtr:SetHide(true);
        m_isViewInitialized = false;
        UIManager:DisablePopupQueue( false );		-- 等待此功能被Forge添加
    end
end
local LEADER_NEUTRAL = {
  [1]="LEADER_DEFAULT_NEUTRAL",
  [2]="LEADER_BARBAROSSA_NEUTRAL",
  [3]="LEADER_CATHERINE_DE_MEDICI_NEUTRAL",
  [4]="LEADER_CLEOPATRA_NEUTRAL",
  [5]="LEADER_GANDHI_NEUTRAL",
  [6]="LEADER_GILGAMESH_NEUTRAL",
  [7]="LEADER_GORGO_NEUTRAL",
  [8]="LEADER_HARDRADA_NEUTRAL",
  [9]="LEADER_HOJO_NEUTRAL",
  [10]="LEADER_MVEMBA_NEUTRAL",
  [11]="LEADER_PEDRO_NEUTRAL",
  [12]="LEADER_PERICLES_NEUTRAL",
  [13]="LEADER_PETER_GREAT_NEUTRAL",
  [14]="LEADER_PHILIP_II_NEUTRAL",
  [15]="LEADER_QIN_NEUTRAL",
  [16]="LEADER_SALADIN_NEUTRAL",
  [17]="LEADER_TOMYRIS_NEUTRAL",
  [18]="LEADER_TRAJAN_NEUTRAL",
  [19]="LEADER_T_ROOSEVELT_NEUTRAL",
  [20]="LEADER_VICTORIA_NEUTRAL",
  [21]="LEADER_BARBARIAN_NEUTRAL",
  [22]="LEADER_MONTEZUMA_NEUTRAL",
  [23]="LEADER_GITARJA_NEUTRAL",
  [24]="LEADER_JAYAVARMAN_NEUTRAL",
  [25]="LEADER_JADWIGA_NEUTRAL",
  [26]="LEADER_AMANITORE_NEUTRAL",
  [27]="LEADER_ALEXANDER_NEUTRAL",
  [28]="LEADER_CYRUS_NEUTRAL",
  [29]="LEADER_JOHN_CURTIN_NEUTRAL",
  [30]="LEADER_CHANDRAGUPTA_NEUTRAL",
  [31]="LEADER_GENGHIS_KHAN_NEUTRAL",
  [32]="LEADER_LAUTARO_NEUTRAL",
  [33]="LEADER_POUNDMAKER_NEUTRAL",
  [34]="LEADER_ROBERT_THE_BRUCE_NEUTRAL",
  [35]="LEADER_SEONDEOK_NEUTRAL",
  [36]="LEADER_SHAKA_NEUTRAL",
  [37]="LEADER_TAMAR_NEUTRAL",
  [38]="LEADER_WILHELMINA_NEUTRAL",
  [39]="LEADER_FREE_CITIES_NEUTRAL",
  [40]="LEADER_DIDO_NEUTRAL",
  [41]="LEADER_ELEANOR_ENGLAND_NEUTRAL",
  [42]="LEADER_ELEANOR_FRANCE_NEUTRAL",
  [43]="LEADER_KRISTINA_NEUTRAL",
  [44]="LEADER_KUPE_NEUTRAL",
  [45]="LEADER_LAURIER_NEUTRAL",
  [46]="LEADER_MANSA_MUSA_NEUTRAL",
  [47]="LEADER_MATTHIAS_CORVINUS_NEUTRAL",
  [48]="LEADER_PACHACUTI_NEUTRAL",
  [49]="LEADER_SULEIMAN_NEUTRAL",
  [50]="LEADER_T_ROOSEVELT_ROUGHRIDER_NEUTRAL",
  [51]="LEADER_ELIZABETH_NEUTRAL",
  [52]="LEADER_HARALD_ALT_NEUTRAL",
  [53]="LEADER_VICTORIA_ALT_NEUTRAL",
  [54]="LEADER_ABRAHAM_LINCOLN_NEUTRAL",
  [55]="LEADER_NZINGA_MBANDE_NEUTRAL",
  [56]="LEADER_SALADIN_ALT_NEUTRAL",
  [57]="LEADER_YONGLE_NEUTRAL",
  [58]="LEADER_WU_ZETIAN_NEUTRAL",
  [59]="LEADER_QIN_ALT_NEUTRAL",
  [60]="LEADER_RAMSES_NEUTRAL",
  [61]="LEADER_CLEOPATRA_ALT_NEUTRAL",
  [62]="LEADER_SUNDIATA_KEITA_NEUTRAL",
  [63]="LEADER_SIMON_BOLIVAR_NEUTRAL",
  [64]="LEADER_LADY_SIX_SKY_NEUTRAL",
  [65]="LEADER_JULIUS_CAESAR_NEUTRAL",
  [66]="LEADER_AMBIORIX_NEUTRAL",
  [67]="LEADER_BASIL_NEUTRAL",
  [68]="LEADER_KUBLAI_KHAN_CHINA_NEUTRAL",
  [69]="LEADER_LADY_TRIEU_NEUTRAL",
  [70]="LEADER_KUBLAI_KHAN_MONGOLIA_NEUTRAL",
  [71]="LEADER_CATHERINE_DE_MEDICI_ALT_NEUTRAL",
  [72]="LEADER_TOKUGAWA_NEUTRAL",
  [73]="LEADER_NADER_SHAH_NEUTRAL",
  [74]="LEADER_SULEIMAN_ALT_NEUTRAL",
  [75]="LEADER_MENELIK_NEUTRAL",
  [76]="LEADER_HAMMURABI_NEUTRAL",
  [77]="LEADER_LUDWIG_NEUTRAL",
  [78]="LEADER_THEODORA_NEUTRAL",
  [79]="LEADER_SEJONG_NEUTRAL",
  [80]="LEADER_JOAO_III_NEUTRAL"
}
-- ------------------------------------------------------------------------------------------------------------------------
local w,h = UIManager:GetScreenSizeVal(); -- 获取屏幕尺寸
local aSizeY = 0;
local ImageID = 1
function Portrait(id)
	ImageID = id
	print("ImageID：", ImageID)
	print("ScreenSizeVal：", w, h)
	Controls.GetSizeTool:SetTexture(LEADER_NEUTRAL[ImageID])
	-- 获得原有Texture大小
	local iSizeX, iSizeY = Controls.GetSizeTool:GetSizeVal()
	print("GetSizeToolSizeX：",iSizeX, iSizeY)
	--  计算Y偏移
	local YOffsetY = math.floor((h * 0.07) + 0.5)

	-- 在当前屏幕显露部分的高度
	aSizeY = h - YOffsetY;
	print("YPKLeaderBox：",aSizeY)
	
	local YSizeX = math.floor((iSizeX * aSizeY / 1004) + 0.5);
	local YSizeY = math.floor((iSizeY * aSizeY / 1004) + 0.5);
	--  计算X偏移 ,需要缩放后的YSizeX才能计算
	local YOffsetX = math.floor((w * 0.7 - YSizeX / 2)  + 0.5)

	print("LeaderAnchorY偏移：",YOffsetX,YOffsetY)
	print("YPKLeaderBox大小：",YSizeX,aSizeY)
	Controls.LeaderAnchorY:SetOffsetVal(YOffsetX,YOffsetY)
	Controls.YPKLeaderBox:SetSizeVal(YSizeX,aSizeY)
	Controls.YPortrait:SetSizeVal(YSizeX, YSizeY)
	print("YPortrait大小：", Controls.YPortrait:GetSizeVal())

	Controls.YPortrait:SetTexture(LEADER_NEUTRAL[ImageID])
	print("YPortrait大小2：", Controls.YPortrait:GetSizeVal())
end
function Initialize()   
    SizeBackgrounds();
    LuaEvents.DiploScene_CinemaSequence.Add(OnLeaderSelect);
    LuaEvents.DiploScene_LeaderSelect.Add(OnLeaderSelect);
    LuaEvents.DiploScene_SceneClosed.Add(UninitializeView);
    LuaEvents.DiploScene_SceneOpened.Add(OnSceneOpened);
    UI.SetLeaderSceneControl(Controls.LeaderScene);
-- =================================
--------------------
--[中心来算方法
-- 从中心向右移动20%，从中心向下移动7%（四舍五入）
local OffsetX,OffsetY = math.floor(w * 0.2 + 0.5), math.floor(((h * 0.07) / 2) + 0.5)
-- 从中心向右移动20%，从中心向下移动7%（四舍五入）
local SizeY = h - (OffsetY * 2);
local SizeX = math.floor((SizeY * 532 / 1004) + 0.5);
print("LeaderAnchorx偏移：",OffsetX,OffsetY)
print("xPKLeaderBox大小：",SizeX,SizeY)
Controls.LeaderAnchorx:SetOffsetVal(OffsetX,OffsetY)
Controls.xPKLeaderBox:SetSizeVal(SizeX,SizeY)
--]]

--[左上来算方法
  Portrait(1)
--]]
----------------------
local screenWidth, screenHeight = UIManager:GetScreenSizeVal();

		if (screenHeight < 768) then
			Controls.pkContainer:SetSizeY(920);
		else
			Controls.pkContainer:SetSizeY(987);
		end

local LEADER_CONTAINER_X = 512;
local offsetX = math.floor((Controls.Portrait:GetSizeX() - LEADER_CONTAINER_X)/2);
if (offsetX > 0) then
	Controls.Portrait:SetOffsetX(- offsetX);
else
	Controls.Portrait:SetOffsetX(0);
end
local ribbonRunsPastCenter:number = 80;
Controls.PortraitContainer:SetSizeX( (screenWidth*0.5) - ribbonRunsPastCenter );

--        local w,h = UIManager:GetScreenSizeVal(); -- 获取屏幕尺寸 
        -- 调整领袖显示位置
--        Controls.LeaderAnchor:SetOffsetX(w - (w/4));
--        Controls.LeaderAnchor:SetOffsetY(h/2);
--        print("pUIOffset: ", UIManager:GetScreenSizeVal())
--        print("pLSOffset: ", Controls.LeaderAnchor:GetScreenOffset())
-------------------------     
-- =================================
    local mods = Modding.GetActiveMods();
    if (mods ~= nil) then
        for i,v in ipairs(mods) do
            if v.Id == TUTORIAL_ID then
                m_isTutorial = true;
                break;
            end
        end
    end

end
Initialize();
function ImagePlaybackTest()
	ImageID  = ImageID + 1
	if ImageID == 81 then ImageID = 1; end 
	Portrait(ImageID)
end

-- 此时1秒换三次图
local timing = 20
function function1()
    timing = timing - 1; --当 timing = 0时既10秒已过
    if timing == 0 then
        --省略你具体每10秒要工作的代码程序
        ImagePlaybackTest()
        timing = 20; -- 重置时间
    end
end

function function2()-- 当需要function1这个循环函数工作时，触发function2()，添加function1
    Events.GameCoreEventPublishComplete.Add(function1)
end

function function3() -- 当不需要function1这个循环函数工作时，触发function3()，结束function1
	Events.GameCoreEventPublishComplete.Remove(function1)
	ImageID = 0;
	ImagePlaybackTest()
end
LuaEvents.PKImagePlaybackTest.Add(function2);
LuaEvents.PKImageStopbackTest.Add(function3);
LuaEvents.PKPortrait.Add(Portrait);


-- =======================================================================
-- 打开绿幕拍摄UI
local OpenScreen = true;
function SwitchGreenScreen()
	local iControl = ContextPtr:LookUpControl("/InGame/Diplomacy/DiplomacyActionView");
	local iControlTable = iControl:GetChildren()
	for i,uiChild in ipairs(iControlTable ) do	
		if 8 < i and i < 13 then
			uiChild:SetShow(OpenScreen);
			Controls.CurtainBackground:SetShow(OpenScreen);
			OpenScreen = false
		end
	end
end
LuaEvents.SwitchScreen.Add(SwitchGreenScreen)

-- =======================================================================